package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.base.service.impl.BaseServiceImpl;
import com.example.common.utils.ApiResult;
import com.example.dao.PersonMapper;
import com.example.dao.SuppliesMapper;
import com.example.dao.SuppliesPropMapper;
import com.example.dao.SuppliesTypeMapper;
import com.example.model.entity.Person;
import com.example.model.entity.Supplies;
import com.example.model.entity.SuppliesType;
import com.example.model.query.PersonQuery;
import com.example.model.query.SuppliesQuery;
import com.example.model.vo.SuppliesVo;
import com.example.service.PersonService;
import com.example.service.SuppliesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PersonServiceImpl extends BaseServiceImpl<PersonMapper, Person> implements PersonService {

    //访问路径
    @Value("${real_url:}")
    private String real_url;
    //真实路径
    @Value("${real_path:}")
    private String realPath;

    @Autowired
    private PersonMapper personMapper;

    @Override
    public Map<Boolean, String> imgUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file){
        Map<Boolean,String> map = new HashMap<Boolean,String>();
        String res = "";
        response.setContentType("text/html; charset=utf-8");
        if(!file.isEmpty()){
            String msg = "";
            //最大文件大小
            long maxSize = 52428800;//50M
            response.setContentType("text/html; charset=UTF-8");
            //检查目录
            File uploadDir = new File(realPath);
            if(!uploadDir.isDirectory()){
                msg = "上传目录不存在，请确认您配置的物理路径是否正确！";
                map.put(false,msg);
                return map;
            }
            //检查目录写权限
            if(!uploadDir.canWrite()){
                msg = "上传目录没有写权限。";
                map.put(false,msg);
                return map;
            }
            //创建文件夹-正式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            sdf = new SimpleDateFormat("hh");
            String hh = sdf.format(new Date());
            sdf = new SimpleDateFormat("mm");
            String mm = sdf.format(new Date());

            String realpathStr = realPath +"/";
            File realFile = new File(realpathStr);
            if (!realFile.exists()) {
                realFile.mkdirs();
            }
            realpathStr += ymd + "/"+ ymd+hh + "/"+ ymd+hh+mm+ "/";
            String realUrlStr = real_url + ymd + "/"+ ymd+hh + "/"+ ymd+hh+mm+ "/";
            File realFile2 = new File(realpathStr);
            if (!realFile2.exists()) {
                realFile2.mkdirs();
            }
            //检查文件大小
            if(file.getSize() > maxSize){
                msg = "上传文件太大,不能超过50M";
                map.put(false,msg);
                return map;
            }
            String fileName = file.getOriginalFilename();
            //检查扩展名
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if(!("gif".equals(fileExt)||"jpg".equals(fileExt)||"jpeg".equals(fileExt)||"png".equals(fileExt)||"bmp".equals(fileExt))){
                msg = "上传文件扩展名是不允许的扩展名。只允许gif,jpg,jpeg,png,bmp格式。";
                map.put(false,msg);
                return map;
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_"   + "." + fileExt;
            try{
                File uploadedFile = new File(realpathStr, newFileName);
                //复制文件到目录下
                file.transferTo(uploadedFile);
            }catch(Exception e){
                msg = "上传文件失败。";
                map.put(false,msg);
                return map;
            }
            String picUrl = realUrlStr+newFileName;
            String picPath = realpathStr+newFileName;
            //res = WebUtils.getDataByCodeAndMsgAndRs(successCode, successMsg, picUrl);
            //res = picUrl;
            map.put(true,picUrl);
            return map;
        }else{
            map.put(false,"上传文件失败");
            return map;
        }
    }

    @Override
    public ApiResult<PersonQuery> pageUserVoByQuery(PersonQuery query) {
        query.setOptimizeCountSql(false);
        Long current = query.getCurrent();
        query.setCurrent(1L);
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Person::getIsValid,1L);
        if(query.getPersonName() != null){
            queryWrapper.lambda().like(Person::getPersonName,query.getPersonName());
        }
        if(query.getPersonTel() != null){
            queryWrapper.lambda().like(Person::getPersonTel,query.getPersonTel());
        }
        Integer total = personMapper.selectCount(queryWrapper);
        query.setTotal(total);
        query.setCurrent(current);
        query.setIsValid(1L);
        personMapper.selectPage(query,queryWrapper);
        List list = query.getRecords();
        for (int i = 0; i < list.size(); i++) {

        }
        return new ApiResult<>(query);
    }

}
